#pragma once
#include <iostream>
#include <memory>
#include <string>
#include "Connection.hpp"
#include "Socket.hpp"
#include "Common.hpp"
#include "Channel.hpp"
// 管理监听
class Reactor;
static const int Defaulted = -1;
class Listener : public Connection
{
public:
    Listener(int port = Defaulted) : port(port),
                                     listen_socket(std::make_unique<SocketMoudle::TcpSocket>())
    {
        listen_socket->BuildListenSocket(port);
        SetNonBlock(listen_socket->GetSockFd()); // 非阻塞
        setEvents(EPOLLIN | EPOLLET);            // 设置为ET模式
    }
    ~Listener() {}
    void Recever() override
    {
        NetAddr client_addr;
        while (true)
        {
            int client_fd = listen_socket->Accept(&client_addr);
             if (client_fd == ACCEPT_ERROR)
                {
                    break;
                }
                else if (client_fd == ACCEPT_CONTINUE)
                {
                    continue;
                }
                else if (client_fd == ACCEPT_DONE)
                {
                    break;
                }
                else
                {
                    // 合法的fd
                    std::shared_ptr<Connection> conn = std::make_shared<Channel>(client_fd);
                    conn->setEvents(EPOLLIN | EPOLLET);
                    if(this->handler!=nullptr){
                        conn->RegisterHandler(this->handler);
                    }
                    getOwner()->Addconnection(conn);
                }
        }
    };
    void Sender() override
    {
    }
    void Excepter() override {}
    int getFd() override
    {
        return listen_socket->GetSockFd();
    }

private:
    int port;
    std::unique_ptr<SocketMoudle::Socket> listen_socket;
};